package com.imcrl.piano.mvc.controller
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.media.SoundLoaderContext;
	import flash.net.URLRequest;
	
	
	/**
	 *  
	 * @author crl
	 * 
	 */	
	public class BgSoundController extends EventDispatcher
	{
		private var sound:Sound;
		
		private var channel:SoundChannel;
		
		private var context:SoundLoaderContext;
		public function BgSoundController()
		{
			sound=new Sound();
			sound.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
			
			context = new SoundLoaderContext(3000, false);
		}
		
		public function start(path:String):void{
			sound.load(new URLRequest(path),context);
			
			if(channel){
				channel.stop();
				channel.removeEventListener(Event.SOUND_COMPLETE,soundCompleteHandler);
			}
			
			channel=sound.play();
			channel.addEventListener(Event.SOUND_COMPLETE,soundCompleteHandler);
		}
		
		
		private function errorHandler(event:Event):void{
			this.soundCompleteHandler(event);
		}
		
		private function soundCompleteHandler(event:Event):void{
			channel.removeEventListener(Event.SOUND_COMPLETE,soundCompleteHandler);
			channel.stop();
			channel=null;
			
			this.dispatchEvent(new Event(Event.COMPLETE));
		}
	}
}